/**
 * 后台接口文件
 */
import requestApi from "src/erm/sscrppublic/common/components/requestApi";
import { ajax } from 'nc-lightapp-front';
import presetVar from './presetVar';
import {toast } from 'nc-lightapp-front';
import getDefDataFromMeta from 'src/erm/sscrppublic/common/utils/getDefDataFromMeta';
import { viewModel } from 'nc-lightapp-front';
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;
import attachments from 'uap/common/components/getAttachmentInfo';
const { getAttachments } = attachments;


let pageCode = presetVar.pageCode;
let requestDomain = '';

const head1 = presetVar.head.head1;
let referResultFilterCondition = null;
let requestApiOverwrite = {
    ...requestApi,
    //单据模板接口
    tpl: (opt) => {
        let domain = '';//'https://mock.yonyoucloud.com/mock/172';
        ajax({
            url: opt.url || `${domain}/nccloud/erm/expenseaccount/FytzTempletAction.do`,
            data: opt.data,
            success: opt.success
        });
    },
    billRecall: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzRecallAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            }

        })
    },
    //判断客户和供应商是否是散户接口
   isFreecust:(opt)=>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/QueryIsFreeCustAction.do`,
            data:opt.data,
            success: (response) => {
                const data = response.data
                if (response.success) {
                    opt.success(data);
                } else {
                    toast({content:data.message,color:'danger'});
                }
            }
        })
    },
    submitBill: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzSubmitAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error: (data) => {
                toast({ content: data.message, color: 'danger' });
            }
        });
    },
    viewBill: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzViewAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            }
        });
    },
    savejkbx: (opt) => {

        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzSaveBillAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error: (data) => {
                toast({ content: data.message, color: 'danger' });
            }
        })
    },
    saveTemp: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzTempSaveBillAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error: (data) => {
                toast({ content: data.message, color: 'danger' });
            }
        })
    },
    billInvalid: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzInvalidBillAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            }
        })
    },
    billEnable: (opt) => {
        //数据适配开始
        opt.data.head[presetVar.head.head1].rows.map((row) => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    row.values[key].value += '';
                }
            }
            return row;
        });
        opt.data.body[presetVar.body.body1].rows.map((row) => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    row.values[key].value += '';
                }
            }
            return row;
        });
        //数据适配结束

        opt.data = {
            ...opt.data,
            uistate: 'add',
            tradetype: presetVar.tradeType,
            ntbCheck: 'N',
            accessorybillid: null,
            fromssc: 'N',
            msg_pk_bill: null,
            billstatus: -1
        }
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqRestartBillAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            }
        })
    },
    billClose: (opt) => {
        //数据适配开始
        opt.data.head[presetVar.head.head1].rows.map((row) => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    row.values[key].value += '';
                }
            }
            return row;
        });
        opt.data.body[presetVar.body.body1].rows.map((row) => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    row.values[key].value += '';
                }
            }
            return row;
        });
        //数据适配结束
        opt.data = {
            ...opt.data,
            tradetype: presetVar.tradeType,
            userjson: "{'pagecode':" + pageCode + "}"
        }
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqCloseBillAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            }
        })
    },
    billRemove: (opt) => {
        //数据适配开始
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzDeleteAction.do`,
            data: opt.data,
            success: (data) => {
                opt.success(data);
            }
        })
    },
    loadData: (opt) => {
        let billdata = setDefData(opt.meta);
        let userjson = { "pagecode": presetVar.nccPageCode, "appcode": presetVar.nccAppCode, templateid: opt.meta.pageid };
        billdata.userjson = JSON.stringify(userjson);
        let props = opt.props;
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzDefDataAction.do?tradetype=${presetVar.tradeType}&uistatus=add`,
            data: billdata,
            success: (data) => {
                console.log('loadData值：', data)

                //数据适配开始

                //referResultFilterCondition = JSON.parse(JSON.parse(data.data.userjson).crossrule);//交叉校验规则设置
                presetVar.reimsrc = JSON.parse(JSON.parse(data.data.userjson).reimsrc);//核心控制项-影响因素
                presetVar.showitemkey = JSON.parse(data.data.userjson).showitemkey;//显示项
                window.presetVar.ratecontorl = JSON.parse(data.data.userjson).RATECONTORL//集团参数NC004“组织汇率是否可编辑
                window.presetVar.zzbwb = JSON.parse(data.data.userjson).ZZBWB//组织币种
                let bodyValues = data.data.bodys[presetVar.body.body1].rows[0].values;

                let bodyAreaArr = [presetVar.body.body1, 'er_cshare_detail&childform2'];
                let numberInitialvalueField = ['bbhl','tax_rate','groupbbhl','globalbbhl','rowno'];
                bodyAreaArr.forEach((bodyArea) => {
                    opt.meta[bodyArea].items.forEach((item) => {
                        let newItem = bodyValues[item.attrcode];
                        if (newItem) {
                            if(item.itemtype != 'number' || numberInitialvalueField.indexOf(item.attrcode) >= 0){
                                item.initialvalue = {
                                    value: newItem.value,
                                    display: newItem.display || newItem.value,
                                };
                            } else{
                                item.initialvalue = {
                                    // TOP 金额字段不需要显示默认值 chengwebc DEL
                                    //20190510 去掉该代码：解决表体精度问题
                                    // scale: newItem.scale
                                };
                            }
                            //20190510 去掉该代码：解决表体精度问题
                            // item.scale = newItem.scale;
    
                            //处理交叉校验规则和参照过滤
                            filterAllRefParm(item, props, bodyArea);
                        }
    
                    });
                })

                let headValues = data.data.head[presetVar.head.head1].rows[0].values;
                for (let attrcode in headValues) {
                    opt.meta[presetVar.head.head1].items.forEach((item) => {
                        if (item.attrcode == attrcode) {
                            item.initialvalue = {
                                value: headValues[attrcode].value,
                                display: headValues[attrcode].display = null ? headValues[attrcode].value : headValues[attrcode].display,
                            };

                            item.scale = headValues[attrcode].scale;

                            //处理交叉校验规则和参照过滤
                            filterAllRefParm(item, props, presetVar.head.head1);
                        }

                    });
                }

                //适配多表头
                if (opt.meta.formrelation) {
                    opt.meta.formrelation[presetVar.head.head1].forEach((item) => {
                        if (opt.meta[item]) {
                            opt.meta[item].items.forEach((key) => {
                                let attrcode = key.attrcode;
                                if (headValues[attrcode]) {
                                    key.initialvalue = {
                                        value: headValues[attrcode].value,
                                        display: headValues[attrcode].display = null ? headValues[attrcode].value : headValues[attrcode].display,
                                    };

                                    key.scale = headValues[attrcode].scale;
                                    //处理交叉校验规则和参照过滤
                                    filterAllRefParm(key, props, presetVar.head.head1);
                                }
                            })
                        }

                    });
                }
                opt.success(opt.meta, data.data);
            }
        })
    },
    changeByHead: (opt) => {
        opt.data = {
            ...opt.data,
            userjson: "{'pagecode':" + pageCode + "}"
        }
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqValueChangedAction.do`,
            data: opt.data,
            success: (data) => {
                //referResultFilterCondition = JSON.parse(JSON.parse(data.data.userjson).crossrule);//交叉校验规则设置
                opt.success(data);
            }
        });
    },
    changeByBody: (opt) => {
        opt.data = {
            ...opt.data,
            userjson: "{'pagecode':" + pageCode + "}"
        }
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqValueChangedAction.do`,
            data: opt.data,
            success: (data) => {
                //referResultFilterCondition = JSON.parse(JSON.parse(data.data.userjson).crossrule);//交叉校验规则设置
                opt.success(data);
            }
        });
    },
    copyBill: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzCopyAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            }
        });
    },
    valueChange: (opt) => {

        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzValueChangeAction.do`,
            data: opt.data,
            async: false,
            success: (data) => {
                data = data.data;
                opt.success(data);
            }
        })
    },
    getUnEditAttributes:(opt) =>{
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/pub/ErmAttributeEditableAction.do`,
            data: opt.data,
            success: (data) => {
                data = data.data;
                opt.success(data);
            },
            error:(data) =>{
                toast({content:data.message,color:'warning'});
            }
        });
    },
    linkRelationBill: (opt) => {

        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/expenseaccount/FytzLinkRelationAction.do`,
            data: opt.data,
            async: false,
            success: (data) => {
                data = data.data;
                opt.success(data);
            }
        })
    },
    /**
    * 获取控制附件修改和必须上传的接口
    */
   getAttachmentControlParams: (opt) => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/ermextendattr/ErmAccessoryControl.do`,
            data: opt.data,
            success: (response) => {
                const data = response.data
                if (data && data.success === 'true') {
                    opt.success(data);                    
                } else {
                    toast({content:data.message,color:'danger'});
                }
            },
            error:(data)=>{
                toast({content:data.message,color:'danger'});
            }
        })
    },
    makebill: (opt) => {
        let srcAppcode ='201102CBSP';
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/makebill/MakeBillAccruedAction.do`,
            data: opt.data,
            success: (res) => {
                console.log('接口返回数据：', res);
                let { data } = res;
                if (!data) {
                    return;
                }
                opt.success(data);
            },
            error: (data) => {
                toast({ content: data.message, color: 'danger' });
            }
        })
    },
    /**
    * 判断附件是否已经上传
    */
    isAttachmentsUploaded: async (billId) => {
        const count = await getAttachments(billId)
        return count > 0
    }
}

async function isUploadedAttachments(props) {
    const billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || presetVar.openBillId;
    //附件控制必传
    if (window.presetVar.attachmentControl && window.presetVar.attachmentControl.necessary) {
        if (!billId) {
            toast({content:"必须上传附件",color:'danger'})
            return false
        }
        const hasUploaded = await requestApiOverwrite.isAttachmentsUploaded(billId)
        if (hasUploaded) {
            return true
        } else {
            toast({content:"必须上传附件",color:'danger'})
            return false
        }
    }
    return true
}

function filterAllRefParm(item, props, flag) {
    let BusinessUnitTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefSqlBuilder';//组织
    let OrgTreeRefFilterPath ='nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder';//组织
    let DeptTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef';//部门
    let CurrtypeRefSqlFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.CurrtypeRefSqlBuilder';//币种
    let PsndocTreeFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PsndocTreeGridRef';//人员
    let SupplierTreeGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.SupplierTreeGridRef';//供应商
    let CustomerTreeGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.CustomerTreeGridRef';//客户
    let PublicDefaultGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder';//公共
    const CustomerVersionTreeGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.CustomerVersionTreeGridRef'
    const SupplierVersionGridRef =  'nccloud.web.erm.action.ref.sqlbuilder.SupplierVersionTreeGridRef'

    function getItemValue(attrcode) {
        let ret;
        switch (flag) {
            case presetVar.head.head1:
                ret = props.form.getAllFormValue(flag).rows[0].values[attrcode] && props.form.getAllFormValue(flag).rows[0].values[attrcode].value
                break;
            case presetVar.body.body1:
                ret = presetVar.currentRowRecord.values[attrcode] && presetVar.currentRowRecord.values[attrcode].value
                break;
            case 'er_cshare_detail&childform2':
                ret = presetVar.currentRowRecord.values[attrcode] && presetVar.currentRowRecord.values[attrcode].value
                break;
            default:
                console.error('未匹配到区域：', flag)
        }
        return ret
    }
    //所属组织，待确定是否需要特殊处理
    if (item.attrcode == 'pk_org') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if(!paramurl.c){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            return { pk_group: getItemValue('pk_group'), TreeRefActionExt: OrgTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y', appcode : paramurl.c}; // 根据pk_group过滤
        };
    }

    //申请单位
    if (item.attrcode == 'apply_org') {

        item.queryCondition = () => {
            return { pk_group: getItemValue('pk_group'), TreeRefActionExt: BusinessUnitTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据pk_group过滤
        };
    }
    //承担单位
    if (item.attrcode == 'assume_org') {
        item.queryCondition = () => {
            return { pk_group: getItemValue('pk_group'), TreeRefActionExt: BusinessUnitTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据pk_group过滤
        };
    }

    //申请部门
    if (item.attrcode == 'assume_dept') {
        item.queryCondition = () => {
            return { pk_org: getItemValue('assume_org'), TreeRefActionExt: DeptTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据apply_org过滤
        };
    }
    //承担部门
    if (item.attrcode == 'fydeptid_v') {
        item.queryCondition = () => {
            return { pk_org: getItemValue('fydwbm_v'), TreeRefActionExt: DeptTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据assume_org过滤
        };
    }
     //承担部门
     if (item.attrcode == 'fydeptid') {
        item.queryCondition = () => {
            return { pk_org: getItemValue('fydwbm'), TreeRefActionExt: DeptTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据assume_org过滤
        };
    }   
     //经办人部门
     if (item.attrcode == 'deptid') {
        item.queryCondition = () => {
            return { pk_org: getItemValue('dwbm'), TreeRefActionExt: DeptTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据assume_org过滤
        };
    }   
     //经办人部门
     if (item.attrcode == 'deptid_v') {
        item.queryCondition = () => {
            return { pk_org: getItemValue('dwbm_v'), TreeRefActionExt: DeptTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据assume_org过滤
        };
    }   
    
    //表头收支项目
    if (item.attrcode == 'szxmid') {
        item.queryCondition = () => {
            //pk_org 用表头的原费用承担单位字段
            return { pk_org: getItemValue('fydwbm'), TreeRefActionExt: BusinessUnitTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据fydwbm_v过滤
        };
    }

    //表体收支项目
    if (item.attrcode == 'pk_iobsclass') {
        item.queryCondition = () => {
            // 后面的pk_org不知道什么场景会有，先注释。 let data = dataValues['assume_org'] == null ? dataValues['pk_org'].value : dataValues['assume_org'].value;
            return { pk_org: getItemValue('assume_org'), TreeRefActionExt: BusinessUnitTreeRefFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据assume_org过滤
        };
        item.queryGridUrl = window.location.origin + "/nccloud/uapbd/ref/InoutBusiClassTreeRef.do";
    }

    // 供应商
    if (item.attrcode == 'hbbm') {
        item.queryCondition = () => {
            //paytarget支付对象，在调整单不适用，先注释
            /* let paytarget = dataValues['paytarget']==null?"":dataValues['paytarget'].value;
            if(paytarget!="1"){
                //收款对象为供应商
                return {pk_org: ''};
            } */
            return { pk_org: getItemValue('fydwbm'), GridRefActionExt: SupplierTreeGridRef, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据pk_org过滤
        };
    }

    //客户
    if (item.attrcode == 'customer') {
        item.queryCondition = () => {
            //paytarget支付对象，在调整单不适用，先注释
            /*let paytarget = dataValues['paytarget']==null?"":dataValues['paytarget'].value;
             if(paytarget!="2"){
                //收款对象为客户
                return { pk_org: ''};
            } */
            return { pk_org: getItemValue('fydwbm'), GridRefActionExt: CustomerTreeGridRef, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据pk_org过滤
        };
    }
    // 供应商版本
    if (item.attrcode == 'hbbm_v') {
        item.queryCondition = () => {
            //paytarget支付对象，在调整单不适用，先注释
            /* let paytarget = dataValues['paytarget']==null?"":dataValues['paytarget'].value;
            if(paytarget!="1"){
                //收款对象为供应商
                return {pk_org: ''};
            } */
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['djrq'].value
            return { pk_org: getItemValue('fydwbm'), queryDate:date, GridRefActionExt:SupplierVersionGridRef, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据pk_org过滤
        };
    }

    //客户
    if (item.attrcode == 'customer_v') {
        item.queryCondition = () => {
            //paytarget支付对象，在调整单不适用，先注释
            /*let paytarget = dataValues['paytarget']==null?"":dataValues['paytarget'].value;
             if(paytarget!="2"){
                //收款对象为客户
                return { pk_org: ''};
            } */
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['djrq'].value
            return { pk_org: getItemValue('fydwbm'), queryDate:date, GridRefActionExt:CustomerVersionTreeGridRef, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' }; // 根据pk_org过滤
        };
    }

    //币种
    if (item.attrcode == 'pk_currtype') {
        item.queryCondition = () => {
            return { TreeRefActionExt: CurrtypeRefSqlFilterPath, DataPowerOperationCode: 'fi',/**使用权组**/isDataPowerEnable: 'Y' };
        };
    }

    // //人员
    if (item.attrcode == 'jkbxr') {
        item.queryCondition = () => {
            let orgPk = getItemValue('dwbm');
            return {
                tradetype: presetVar.tradeType,
                pk_org: orgPk,
                //pk_dept: getItemValue('deptid'),
                org_id: orgPk,
                GridRefActionExt: PsndocTreeFilterPath,
                DataPowerOperationCode: 'fi',/**使用权组**/
                isDataPowerEnable: 'Y'
            }; // 根据assume_org过滤
        };
    }


    let bodys = Object.values(presetVar.body);
    let bodyarr = [];
    bodys.forEach((one) => {
        bodyarr[bodyarr.length] = one;
    })
    //处理交叉校验规则
    if (item.itemtype == 'refer') {
        let oldQueryCondition = item.queryCondition;
        let crossrule_itemkey = item.attrcode;
        item.queryCondition = (obj) => {
            let crossrule_datasout = props.createExtCardData(props.meta.getMeta().code, presetVar.head.head1, bodyarr);
            let crossrule_tradetype = props.form.getFormItemsValue(presetVar.head.head1, 'djlxbm').value;
            let crossrule_org = flag === presetVar.head.head1 ? _.get(props.form.getAllFormValue(presetVar.head.head1), `rows[0].values.fydwbm_v.value`, ''): getBodyValueBeforeRefRequest(props, flag, 'assume_org');
            let crossrule_datatypes = 'extbillcard';
            let isHead = flag == presetVar.head.head1 ? "true" : "false"
        
            let crossrule_datas = null;
            if (flag != presetVar.head.head1 && presetVar.currentRowRecord) {
                crossrule_datasout.bodys[flag].rows = [presetVar.currentRowRecord]
                crossrule_datas = crossrule_datasout;
            } else {
                crossrule_datas = crossrule_datasout;
            }
            
            let conditionFlag = true;
            if (oldQueryCondition == null || oldQueryCondition == undefined || oldQueryCondition == 'undefined')
                conditionFlag = false;

            let oldData = '';
            if (conditionFlag)
                oldData = oldQueryCondition();
            if (oldData == null || oldData == undefined || oldData == 'undefined')
                oldData = '';

            let config = {
                crossrule_datas: JSON.stringify(crossrule_datas),
                crossrule_tradetype: crossrule_tradetype,
                crossrule_org: crossrule_org,
                crossrule_datatypes: crossrule_datatypes,
                crossrule_area: flag,
                crossrule_itemkey: crossrule_itemkey,
                crossrule_isHead : isHead,
                ...oldData
            };

            //参照类型的自定义项字段增加组织过滤
            if(!oldData.pk_org && obj && obj.attrcode && (obj.attrcode.startsWith("defitem") || obj.attrcode.startsWith("zyx") || obj.datatype == "56")){
                config.pk_org = crossrule_org;
            }

            if (obj == undefined || obj == null || obj.refType == undefined || obj.refType == null) {
                if (config.TreeRefActionExt == null || config.TreeRefActionExt == undefined || config.TreeRefActionExt.length == 0)
                    config.TreeRefActionExt = PublicDefaultGridRef;
                return config;
            }

            if (obj.refType == 'grid') {
                if (config.GridRefActionExt == null || config.GridRefActionExt == undefined || config.GridRefActionExt.length == 0)
                    config.GridRefActionExt = PublicDefaultGridRef;
            } else if (obj.refType == 'tree') {
                if (config.TreeRefActionExt == null || config.TreeRefActionExt == undefined || config.TreeRefActionExt.length == 0)
                    config.TreeRefActionExt = PublicDefaultGridRef;
            } else if (obj.refType == 'gridTree') {
                if (config.GridRefActionExt == null || config.GridRefActionExt == undefined || config.GridRefActionExt.length == 0)
                    config.GridRefActionExt = PublicDefaultGridRef;
            }


            return config;
        }
    }


}


function genReqParamForLoadData(meta) {
    let reqData = {
        head: {},
        body: {}
    }
    for (let areaCode in meta) {
        let areaData = meta[areaCode];
        //满足以下条件才是区域。 relationcode用来区分cardTable
        if (!areaData.moduletype || !areaData.items || areaData.hasOwnProperty('relationcode')) {
            continue;
        }
        //设定区域初始状态
        switch (areaData.moduletype) {
            case 'form':
                reqData.head[areaCode] = {
                    areaType: 'form',
                    "areacode": areaCode,
                    rows: [{
                        'values': {}
                    }]
                }
                areaData.items.forEach((item) => {
                    reqData.head[areaCode].rows[0].values[item.attrcode] = {
                        value: null
                    };
                });
                break;
            case 'table':
                reqData.body[areaCode] = {
                    areaType: 'table',
                    "areacode": areaCode,
                    rows: [{
                        'values': {}
                    }]
                }
                areaData.items.forEach((item) => {
                    reqData.body[areaCode].rows[0].values[item.attrcode] = {
                        value: null
                    };
                });
                break;
            case 'search':
                break;
        }
    }
    return reqData;
}


function setDefData(meta) {
    // TOP 修改取模版默认值方法（修改前模版默认值无法默认带出） 190225 MOD
    // let json = { "head": {}, "bodys": {} };
    // json.head = {
    //     "pageid": "nc.vo.ep.bx.BXHeaderVO"
    // };
    // json.head.arap_bxzb = {
    //     "areaType": "form",
    //     "areacode": "arap_bxzb",
    //     "rows": []
    // };
    // let body = {};
    // for (let table in meta.gridrelation) {
    //     body[table] = {
    //         "areaType": "table",
    //         "areacode": table,
    //         "rows": []
    //     };
    //     let bodyrowValue = {};
    //     meta[table].items.forEach((item) => {
    //         let code = item.attrcode;
    //         bodyrowValue[code] = {
    //             "display": null,
    //             "value": null
    //         };
    //     });
    //     body[table].rows[0] = {
    //         values: bodyrowValue
    //     }
    // }

    // let head_values = {};
    // meta.arap_bxzb.items.forEach((item) => {
    //     let code = item.attrcode;
    //     head_values[code] = {
    //         "display": null,
    //         "value": null
    //     }

    // });
    // json.head.arap_bxzb.rows[0] = { values: head_values }
    // json.bodys = body;
    // return json;
    return getDefDataFromMeta(meta, 'nc.vo.ep.bx.BXHeaderVO');
    // BTM 修改取模版默认值方法
}

export default requestApiOverwrite;
export {
    isUploadedAttachments
}

// 1903方式，参数列表在url中，改为根据url的page属性从session中获取
// function getRequest1(url) {
//     if (!url)
//         url = document.location.search;
//     var theRequest = new Object();
//     if (url.indexOf("?") != -1) {
//         var str = url.substring(url.indexOf("?") + 1);
//         var strs = str.split("&");
//         for (var i = 0; i < strs.length; i++) {
//             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
//         }
//     }
//     return theRequest;
// }
// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);        
    } else {
        sessionInfo = url;
    }
    

    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}

/**
 * 表体参照请求前获取表体行某字段的值
 * @param {} props 
 */
 function getBodyValueBeforeRefRequest(props, tablecode, key){
    let clickRow = props.cardTable.getClickRowIndex(tablecode)
    if (clickRow){
        if(clickRow.record.values[key]) {
            return clickRow.record.values[key].value;
        } else {
            toast({content:`表体模板缺少配置项${key}`, color:'danger'})
            return null
        }
    }else{
        let currentIndex = props.cardTable.getCurrentIndex(tablecode);
        return props.cardTable.getDataByIndex(tablecode, currentIndex).values[key].value;
    }
    
}